package mysql

import (
	"fmt"
	"shortUrl/models"
	"shortUrl/setting"
	"time"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)
var (
	DB *gorm.DB
)
func Init(mysqlConf setting.MysqlConfig) error{
	newLogger := logger.New(
		zap.NewStdLog(zap.L()), // 写入到zap日志
		logger.Config{
		  SlowThreshold:              time.Second,   // Slow SQL threshold
		  LogLevel:                   logger.Silent, // Log level
		  IgnoreRecordNotFoundError: true,           // Ignore ErrRecordNotFound error for logger
		  ParameterizedQueries:      true,           // Don't include params in the SQL log
		  Colorful:                  false,          // Disable color
		},
	  )
	//mysqlConf := setting.Conf.MysqlConfig
	fmt.Println(mysqlConf,"mysqlConf")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User,
	  	mysqlConf.PassWord,
		mysqlConf.Host,
		mysqlConf.Port,
		mysqlConf.DBname,
	)

	db,err := gorm.Open(mysql.Open(dsn),&gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable:true,
		},
		Logger : newLogger,
	})
	if err != nil{
		return err
	}

	sqltx,_ := db.DB()
	sqltx.SetMaxIdleConns(mysqlConf.SetmaxidleConns)
	sqltx.SetMaxOpenConns(mysqlConf.SetmaxopenConns)
	fmt.Println("数据库链接成功")
	DB = db
	err = DB.AutoMigrate(&models.Urls{})
	if err != nil{
		fmt.Println("数据库链接成功",err)
	}
	return nil
}